package com.gdc.miaosha.config;

import com.gdc.miaosha.entity.User;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Description: 用户参数解析(当前的参数解析类，只会在请求方法参数包含支持类型时，才会进行解析方法中)
 *
 *  目前使用 用户上下文，因此此解析类可以不再使用
 *
 * @author: gdc
 * @date: 2022/4/4
 * @version 1.0
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        return User.class == clazz;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        return UserContext.getUser();
    }

    /*@Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // 获取请求对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        // 获取响应对象
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        if (ArrayUtil.isEmpty(request.getCookies())) {
            return null;
        }

        // 获取cookie值中是否包含 token信息
        String token = Lists.newArrayList(request.getCookies()).stream()
                .filter(cookie -> Objects.equals(cookie.getName(), CommonConstant.COOKIE_KEY))
                .map(Cookie::getValue)
                .findFirst()
                .orElse(null);

        User user = userService.getByToken(token);
        if (Objects.isNull(user)) {
            return null;
        }

        // 更新Redis中 Token 的过期时间
        RedisUtil.set(RedisConstant.TOKEN_PREFIX + token, JSON.toJSONString(user), EXPIRED_2_DAY);

        // 更新浏览器 Cookie 中 token值的过期时间
        Cookie cookie = new Cookie(COOKIE_KEY, token);
        cookie.setMaxAge(EXPIRED_2_DAY);
        cookie.setPath("/");
        response.addCookie(cookie);
        return user;
    }*/
}
